package com.daocao.ds.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ImageView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.daocao.ds.Application;
import com.daocao.ds.MainActivity;
import com.daocao.ds.R;
import com.daocao.ds.api.Api;
import com.daocao.ds.api.bean.InitAppBean;
import com.daocao.ds.api.model.InitAppModel;
import com.daocao.ds.base.BaseActivity;
import com.daocao.ds.constant.Const;
import com.daocao.ds.constant.UserInfoGlobal;
import com.daocao.ds.util.ACache;
import com.daocao.ds.util.PackageUtil;
import com.daocao.ds.util.PreferenceUtils;
import com.daocao.ds.util.RBInfo;
import com.daocao.ds.util.RxLifeUtil;
import com.daocao.ds.util.Util;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.functions.Function;


/**
 * Created by xsooy-pc on 2017/10/16.
 */

public class SplashActivity extends BaseActivity implements AMapLocationListener {
    @BindView(R.id.img_splash)
    ImageView imgSplash;
    private Unbinder unbiner;
    private ACache aCache;
    //    @BindView(R.id.txt_title)
//    TextView txtTitle;
    //声明mlocationClient对象
    public AMapLocationClient mlocationClient;
    //声明mLocationOption对象
    public AMapLocationClientOption mLocationOption = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        initBar();
        unbiner = ButterKnife.bind(this);
        init();
        initLocation();
    }

    private void initLocation() {

        mlocationClient = new AMapLocationClient(this);
//初始化定位参数
        mLocationOption = new AMapLocationClientOption();
//设置定位监听
        mlocationClient.setLocationListener(this);
//设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//设置定位间隔,单位毫秒,默认为2000ms
//        mLocationOption.setInterval(2000);
        mLocationOption.setOnceLocation(true);
//设置定位参数
        mlocationClient.setLocationOption(mLocationOption);
// 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
// 注意设置合适的定位时间的间隔（最小间隔支持为1000ms），并且在合适时间调用stopLocation()方法来取消定位请求
// 在定位结束后，在合适的生命周期调用onDestroy()方法
// 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
//启动定位
        mlocationClient.startLocation();
//        checkPermission(new CheckPermListener() {
//            @Override
//            public void superPermission() {
//                mlocationClient.startLocation();
//            }
//        }, R.string.location_permission, R.string.get_location, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION);


    }

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (amapLocation != null) {
//            Log.i("dasdasdadsasdasda", "成功" + amapLocation.getErrorCode() + "定位：" + amapLocation.getLatitude() + "," + amapLocation.getLongitude());

            if (amapLocation.getErrorCode() == 0) {
                //定位成功回调信息，设置相关消息
                PreferenceUtils.putDouble(Application.getInstance(), Const.KEY.LAT, amapLocation.getLatitude());
                PreferenceUtils.putDouble(Application.getInstance(), Const.KEY.LNG, amapLocation.getLongitude());
                initRequest(amapLocation.getLatitude(), amapLocation.getLongitude());
            } else {
                //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                initRequest(amapLocation.getLatitude(), amapLocation.getLongitude());
            }
        }
    }

    private void init() {
        aCache = ACache.get(this);
    }


    private void doJump() {
//        通过修改不同的key，有很多个手势密码
        String gesturePassword = aCache.getAsString(Const.GESTURE_PASSWORD);
        if (gesturePassword == null || "".equals(gesturePassword)) {
            Intent intent = new Intent(SplashActivity.this, CreateGestureActivity.class);
            startActivity(intent);
            finish();
        } else {
            Intent intent = new Intent(SplashActivity.this, GestureLoginActivity.class);
            startActivity(intent);
            finish();
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        imgSplash.setImageResource(0);
        unbiner.unbind();
        if (mlocationClient != null) {
            mlocationClient.unRegisterLocationListener(this);
            mlocationClient.onDestroy();
            mlocationClient = null;
        }
    }

    private void initRequest(double lat, double lang) {
//        if (!Network.checkNetwork(this)) {
//            ToastUtil.show(this, "网络连接失败");
//            return;
//        }

        InitAppBean bean = new InitAppBean();
        bean.client_type = "app";
        bean.device_id = RBInfo.getInstance().getUniquePsuedoID();

        bean.user_agent = RBInfo.getInstance().getUserAgent();

        bean.os = "Android";
        bean.os_version = RBInfo.getInstance().getOSVersion();
//        Log.i("dadaddas",RBInfo.getInstance().getNativePhoneNumber());
        bean.browser = "android";
        bean.browser_version = "1.0";
        bean.mobile_brand = RBInfo.getInstance().getBrand();
        bean.mobile_model = RBInfo.getInstance().getModel();
        bean.app_version = PackageUtil.getVersionName(this);
//        double lat = PreferenceUtils.getDouble(BaseContext.getApplicationContext(), Const.KEY.LAT, -1);
//        double lng = PreferenceUtils.getDouble(BaseContext.getApplicationContext(), Const.KEY.LNG, -1);
//        if (lat > 0 && lng > 0) {
        bean.lat = lat + "";
        bean.lang = lang + "";
        PreferenceUtils.putString(this, "lat", lat + "");
        PreferenceUtils.putString(this, "lng", lang + "");

//        }
        Api.api_service.getInitInfo(bean).compose(RxLifeUtil.NoErrorOn(this))
                .doOnError(throwable -> {
                    Util.startActivity(this, MainActivity.class);
//                    doJump();
                    finish();
                })
                .onErrorResumeNext(new Function<Throwable, ObservableSource<? extends InitAppModel>>() {
                    @Override
                    public ObservableSource<? extends InitAppModel> apply(Throwable throwable) throws Exception {
                        throwable.printStackTrace();
                        return Observable.empty();
                    }
                }).
                subscribe(result -> {
//                    if(result.datas!=null){
//                        UserInfoGlobal.saveInitData(result.datas);
//                    }
//
//                    Util.startActivity(this, MainActivity.class);
//                    finish();
                    saveData(result);
                });
    }

    private void saveData(InitAppModel result) {
        if (result.datas != null) {
            UserInfoGlobal.saveInitData(result.datas);
        }
//        if (PreferenceUtils.getBoolean(this, "first_guide", true)) {
//            startActivity(new Intent(SplashActivity.this, GuideActivity.class));
//            overridePendingTransition(R.anim.splash_in, R.anim.splash_out);
//            finish();
//        }
//        else {
            if (UserInfoGlobal.getIsOpenGuesture() && isSetGuesture() && UserInfoGlobal.checkLogin()) {
                Util.startActivity(this, MainActivity.class);
                Util.startActivity(this, GestureLoginActivity.class);
                finish();
            } else {
                Util.startActivity(this, MainActivity.class);
                finish();
            }

//        }
    }


}
